package com.cqie.controller.medical;

import com.cqie.dto.medical.AddMedicalDrugInfoDto;
import com.cqie.dto.medical.UpdateMedicalDrugInfoDto;
import com.cqie.entity.MedicalDrugInfo;
import com.cqie.exception.SpecialException;
import com.cqie.service.IMedicalDrugInfoService;
import com.cqie.util.ResultTemplate;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

import static com.cqie.constant.FileUploadConstant.FILE_UPLOAD_PATH;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 不吃海鲜
 * @since 2024-12-04
 */

@Tag(name = "药品信息Controller", description = "描述：药品信息接口")
@Slf4j
@RestController
@RequestMapping({"/api/v1.0/medicalDrugInfo", "/api/v1/medicalDrugInfo"})
public class MedicalDrugInfoController {

    private final IMedicalDrugInfoService medicalDrugInfoService;

    public MedicalDrugInfoController(IMedicalDrugInfoService medicalDrugInfoService) {
        this.medicalDrugInfoService = medicalDrugInfoService;
    }

    @Operation(summary = "新增药品信息")
    @PostMapping("/saveMedicalDrugInfo")
    public ResultTemplate<Boolean> saveMedicalDrugInfo(@RequestBody AddMedicalDrugInfoDto addMedicalDrugInfoDto) throws SpecialException {
        return ResultTemplate.Success(medicalDrugInfoService.saveMedicalDrugInfo(addMedicalDrugInfoDto));
    }

    @Operation(summary = "查看药品信息List")
    @GetMapping("/getMedicalDrugInfoList")
    public ResultTemplate<List<MedicalDrugInfo>> getMedicalDrugInfoList(@RequestParam(required = false) String likeQuery,
                                                                        @RequestParam(required = false) String drugType,
                                                                        @RequestParam(defaultValue = "12", required =
                                                                                false) Integer pageSize,
                                                                        @RequestParam(defaultValue = "1", required =
                                                                                false) Integer pageIndex) throws SpecialException {
        return ResultTemplate.Success(medicalDrugInfoService.getMedicalDrugInfoList(likeQuery, drugType, pageSize,
                pageIndex));
    }

    @Operation(summary = "查看详细药品信息")
    @GetMapping("/getMedicalDrugInfoByDrugId")
    public ResultTemplate<MedicalDrugInfo> getMedicalDrugInfo(@RequestParam Integer drugId) throws SpecialException {
        return ResultTemplate.Success(medicalDrugInfoService.getById(drugId));
    }

    @Operation(summary = "删除药品信息")
    @GetMapping("/deleteMedicalDrugInfo")
    public ResultTemplate<Boolean> deleteMedicalDrugInfo(@RequestParam Integer drugId) throws SpecialException {
        return ResultTemplate.Success(medicalDrugInfoService.deleteMedicalDrugInfo(drugId));
    }

    @Operation(summary = "根据药品编号模糊查询")
    @Parameters({
            @Parameter(name = "likeQuery", description = "模糊查询药品编号")
    })
    @GetMapping("/getMedicalDrugInfoByDrugCode")
    public ResultTemplate<List<AddMedicalDrugInfoDto>> getMedicalDrugInfoByDrugCode(@RequestParam(required = false) String drugCode) throws SpecialException {
        return ResultTemplate.Success(medicalDrugInfoService.getMedicalDrugInfoByDrugCode(drugCode));
    }

    @Operation(summary = "上传药品图片")
    @PostMapping("/uploadMedicalDrugInfoImg")
    @CrossOrigin(origins = "/https://localhost:5137")
    public ResultTemplate<Boolean> uploadMedicalDrugInfoImg(@RequestParam("file") MultipartFile file, @RequestParam(
            "drugId") Integer drugId) throws SpecialException {

        log.info("Received file upload request");
        try {
            // 检查参数
            if (file.isEmpty() || drugId == null) {
                return ResultTemplate.Failed("参数不能为空");
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (!contentType.startsWith("image/")) {
                return ResultTemplate.Failed("只能上传图片文件");
            }

            // 获取文件名
            String originalFilename = file.getOriginalFilename();

            // 生成新的文件名(避免文件名冲突)
            String newFileName = UUID.randomUUID().toString() +
                    originalFilename.substring(originalFilename.lastIndexOf("."));

            // 指定存储路径
            String uploadPath = FILE_UPLOAD_PATH;
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 保存文件
            File destFile = new File(uploadPath + File.separator + newFileName);
            file.transferTo(destFile);

            // 构建图片URL
            String imageUrl = FILE_UPLOAD_PATH + newFileName;

            // 更新数据库中的药品图片URL
            MedicalDrugInfo drugInfo = new MedicalDrugInfo();
            drugInfo.setDrugId(drugId);
            drugInfo.setDrugPhoto(imageUrl);

            // 调用service更新药品图片
            boolean updated = medicalDrugInfoService.updateDrugPhoto(drugInfo);

            if (!updated) {
                return ResultTemplate.Failed("更新药品图片失败");
            }

            return ResultTemplate.Success(true);

        } catch (IOException e) {
            log.error("上传图片失败", e);
            return ResultTemplate.Failed("上传图片失败: " + e.getMessage());
        }catch (MultipartException e) {
            throw new SpecialException("Failed to upload file: " + e.getMessage());
        }
    }

    @Operation(summary = "更新药品")
    @PostMapping("/updateMedicalDrugInfo")
    public ResultTemplate<Boolean> updateMedicalDrugInfo(@RequestBody UpdateMedicalDrugInfoDto updateMedicalDrugInfoDto) throws SpecialException {
        return ResultTemplate.Success(medicalDrugInfoService.updateMedicalDrugInfo(updateMedicalDrugInfoDto));
    }



}